<template>
  <Select
    class="select-store"
    placeholder="请选择门店"
    v-model="currValue"
    filterable
    remote
    ref="storeName"
    :loading="loading"
    clearable
    :label-in-value='isLabelInvalue'
    @on-change="onchange"
    @on-query-change="remote"
    @on-open-change="onOpen">
    <Option v-for="item in storeList" :value="item.id" :key="item.id" :label="item.labelAll">
      <span>{{item.label}}</span>
      <p>联系人：{{item.ownerName}}-{{item.storePhone}}</p>
    </Option>
  </Select>
</template>
<script>
  import { debounce } from '@/util'
  export default {
    props: {
      visitName: {
        type: String,
        default: ''
      },
      value: {
        type: [String, Number],
        default: ''
      },
      isLabelInvalue: {
        type: Boolean,
        default: false
      },
      showAddress: {
        type: Boolean,
        default: null
      }
    },
    data() {
      return {
        storeList: [],
        loading: false,
        name: ''
      }
    },
    computed: {
      currValue: {
        get() {
          return this.value
        },
        set(v) {
          this.$emit('input', v || '')
        }
      }
    },
    mounted() {
      // this.getDetailData(this.name)
      if (this.visitName) {
        this.name = this.visitName
        this.getDetailData(this.name)
      }
    },
    methods: {
      onchange(val) {
        let item = this.storeList.find(item => item.id === val) || {}
        this.$emit('on-change', val, item)
      },
      onOpen(isOpen) {
        if (isOpen) this.getDetailData(this.name)
      },
      remote(query='') {
        this.name = query
        this.getDetailData(query)
      },
      getDetailData: debounce(function d(query='') {
        this.loading = true
        this.name = query
        let storeName = query ? query.split('-')[0] : ''
        let param = {
          storeName
        }
        return this.$ajaxGet("/tiger/store/page", param).then(data => {
          this.loading = false
          this.storeList = (data.records || []).map(item => {
            let { storeName, ownerName, storePhone } = item
            let labelAll = `${storeName}-${ownerName}-${storePhone}`
            return {
              id: item.storeId,
              label: storeName,
              storeContractId: item.id,
              ownerName,
              storePhone,
              labelAll
            }
          })
        })
      }, 400)
    }
  }
</script>
<style lang="less">
.select-store {
  .ivu-select-item {
    border-bottom: 1px dotted #DBDBDB;
  }
}
</style>
